package com.xtz.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.xtz.domain.Dish;
import com.xtz.domain.DishFlavor;
import com.xtz.dto.AddDishDto;
import com.xtz.dto.AddDishFlavorDto;
import com.xtz.mapper.AdminDishMapper;
import com.xtz.service.AdminDishService;
import com.xtz.vo.DishPageVo;
import com.xtz.vo.DishVo;
import com.xtz.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * date: 2022/5/9 21:10
 *
 * @author xietianze
 */
@RestController
@RequestMapping("dish")
public class DishController {

    @Autowired
    private AdminDishService adminDishService;
    @PostMapping
    public Result addDish(@RequestBody AddDishDto dto){
        if (Objects.isNull(dto)){
            return new Result(0,"参数不能为空",null,null);
        }else{

            String s = new Snowflake().nextIdStr();
            dto.setId(s);
            Boolean a = adminDishService.addDish(dto);
            AddDishFlavorDto addDishFlavorDto = new AddDishFlavorDto();
            BeanUtils.copyProperties(dto,addDishFlavorDto);

            List<DishFlavor> flavors = dto.getFlavors();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dto.getId());
                adminDishService.addDishFlavor(flavor);
            }
            if (a){
                return new Result(1,null,"成功",null);
            }return new Result(0,null,"失败",null);

        }

    }

    @GetMapping("/list")
    public Result getdishlist(Dish dish){
        /*//实现步骤
        //1. 查询主表列表
        //2. 提取主表中主键 dishId => 集合
        //3. 将这个集合作为查询条件，去查询从表 in()
        //4. 将两个集合进行拼装（两次循环）
        //查询菜品列表
        //条件状态为1的菜品，分类id用于连表
        HashMap<String, Object> condition = new HashMap<>(2);
        condition.put("categoryId",dish.getCategoryId());
        condition.put("status",dish.getStatus());
        List<DishVo> list = adminDishService.getListByCondition(condition);
        if (CollUtil.isEmpty(list)) {
            return new Result(0,null,new ArrayList<>(),null);
        }
        // 步骤二：从菜品列表中提出DishId，该id为关联flavor表的外键

       List<String> dishIdList2 = new ArrayList<>();
        //过滤集合中的空对象（避免后续操作，产生空指针）
       if (CollUtil.isEmpty(list)) {
           return null;
       }
       for (DishVo dishVo : list) {
           if (dishVo == null) {
               continue;
           }

           dishIdList2.add(dishVo.getId());
       }
       //三、使用上一步提出的DishId，查询出所有相关的口味信息
        List<DishFlavor> dishFlavorList = adminDishService.getDishFlavor(dishIdList2);

       //四：遍历菜品列表，并遍历口味列表，进行匹配组装
        List<DishVo> voList = new ArrayList<>();
        // 遍历主表
        for (DishVo item : list) {
            if (Objects.isNull(item)) {
                continue;
            }

            // 主表的信息，复制到 vo 里面
            DishVo vo = new DishVo();
            BeanUtils.copyProperties(item, vo);

            // 遍历副表
            List<DishFlavor> dishFlavors = new ArrayList<>();
            for (DishFlavor dishFlavor : dishFlavorList) {
                if (Objects.isNull(dishFlavor)) {
                    continue;
                }

                // 拿本条主表的id 和 副表的dish_id进行比对
                if (!dishFlavor.getDishId().equals(item.getId())) {
                    // 比对不上，就跳过
                    continue;
                }

                // 比对上了，加入到一个集合
                dishFlavors.add(dishFlavor);
            }

            vo.setFlavors(dishFlavors);
            voList.add(vo);
        }


        return new Result(1,null,voList,null);*/

        //根据分类id，查出所有菜品
        List<DishVo> dishList = adminDishService.getListByCategoryId(dish.getCategoryId());
        //查出所有菜品信息
        List<DishVo> voList = new ArrayList<>();
        //每条菜品都会对应一个口味
        for (DishVo dishVo : dishList) {
            //获取每次遍历到的菜品id
            String dishId = dishVo.getId();
            //根据每次遍历到的菜品id，去查询对应的口味信息
            List<DishFlavor> flavors = adminDishService.getFlavorByDishId(dishId);
            //将数据组装到vo结构中
            DishVo vo = new DishVo();
            vo.setFlavors(flavors);
            BeanUtils.copyProperties(dishVo,vo);

            voList.add(vo);


        }
        return new Result(1,null,voList,null);
    }


    /**
     * 根据id查询菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getdishById(@PathVariable String id){
        Dish dish = adminDishService.selectById(id);
        String dishId = dish.getId();
        //根据id查找口味表
        List<DishFlavor> list1 = adminDishService.getFlavorByDishId(dishId);

        List<DishFlavor> list = new ArrayList<>();
        // 遍历口味添加到集合
        for (DishFlavor flavors : list1) {
            if (!Objects.isNull(flavors)) {
                list.add(flavors);
            }
        }
        dish.setFlavors(list);
        return new Result(1, "查询成功", dish, null);
    }

    @DeleteMapping()
    public Result deleteByIds(@RequestParam List<String> ids){
        Result result = adminDishService.deleteByIds(ids);
        return result;
    }

    /**
     * 分页
     * @param name
     * @param page
     * @param pageSize
     * @param type
     * @return
     */
    @GetMapping("/page")
    public Result page(@RequestParam(required = false,defaultValue = "") String name,
                       @RequestParam Integer page,
                       @RequestParam Integer pageSize,
                       @RequestParam(required = false,defaultValue = "") String type){
        List<DishVo> dishPageByNamelist = adminDishService.getDishPageByName(page, pageSize, name,type);

        Long countByName = adminDishService.getCountByName(name);

        DishPageVo dishPageVo = new DishPageVo();
        dishPageVo.setRecords(dishPageByNamelist);
        dishPageVo.setSize(pageSize);
        dishPageVo.setCurrent(page);
        dishPageVo.setTotal(countByName.intValue());

        return new Result(1,null,dishPageVo,null);
    }

    @PutMapping
    public Result updatedish(@RequestBody Dish dish){
        Boolean result = adminDishService.update(dish);
        int code = result?1:0;
        String data = result ? "chenggong" : "shibai";
        return new Result(code,null,data,null);
    }

    @PostMapping("/status/{status}")
    public Result setStatus(@PathVariable("status")Integer status, @RequestParam("ids") List<String> id) {
        Boolean result = adminDishService.updateStatus(status, id);

        Integer code = result ? 1 : 0;
        String s = result ? "成功" : "失败";

        return new Result(code, null,s, null);

    }


}
